package utils

import (
	"context"
	"errors"
	"log"

	"github.com/go-micro/plugins/v4/registry/consul"
	"github.com/go-micro/plugins/v4/registry/etcd"
	"github.com/go-micro/plugins/v4/registry/nacos"
	"github.com/go-micro/plugins/v4/wrapper/breaker/hystrix"
	"github.com/hashicorp/consul/api"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/urfave/cli/v2"
	"go-micro.dev/v4"
	merrors "go-micro.dev/v4/errors"
	"go-micro.dev/v4/registry"
)

/*
 +----------------------------------------------------------------------
 + Title        : go-micro微服务客户端
 + Author       : huwl
 + Version      : 1.0.0
 + Initial-Time : 2018-01-06
 + Last-time    : 这个文件最后修改的时间 + 修改人的名称
 + Desc         : 创建go-micro微服务客户端，支持consul、nacos、etcd
 +----------------------------------------------------------------------
*/

var MicroServer micro.Service

func init() {
	var registryInstance registry.Registry

	//获取consul、nacos、etcd配置信息
	config, err := GetConfig(ServiceDiscovery, "yml")
	if err != nil {
		log.Fatalln("读取"+ServiceDiscovery+"配置中心错误：", err)
	}

	switch ServiceDiscovery {
	case "consul":
		//集成consul
		registryInstance = consul.NewRegistry(
			registry.Addrs(config.GetStringSlice(Env+".addrs")...),
			consul.Config(&api.Config{
				Token: config.GetString(Env + ".secret_id"),
			}),
		)

	case "nacos":
		//集成nacos
		registryInstance = nacos.NewRegistry(func(op *registry.Options) {
			op.Addrs = config.GetStringSlice(Env + ".addrs")
		}, nacos.WithClientConfig(constant.ClientConfig{
			NamespaceId: config.GetString(Env + ".name_space_id"),
			Username:    config.GetString(Env + ".username"),
			Password:    config.GetString(Env + ".password"),
		}))

	case "etcd":
		//集成etcd
		registryInstance = etcd.NewRegistry(func(op *registry.Options) {
			//地址
			op.Addrs = config.GetStringSlice(Env + ".addrs")
			//密码
			// etcd.Auth("gangan", "123")
		}, etcd.Auth(config.GetString(Env+".username"), config.GetString(Env+".password")))
	}

	// 配置jaeger连接
	// jaegerTracer, closer, err := NewJaegerTracer()
	// if err != nil {
	// 	log.Fatal(err)
	// }
	// defer closer.Close()

	// 创建微服务
	MicroServer = micro.NewService(
		micro.Registry(registryInstance),
		micro.Flags(&cli.StringFlag{
			Name:  "env",
			Usage: "The environment",
			Value: "dev",
		}),
		micro.WrapClient(hystrix.NewClientWrapper(hystrix.WithFilter(func(ctx context.Context, err error) bool {
			var merr *merrors.Error
			return errors.As(err, &merr)
		}))),

		// micro.WrapClient(opentracing.NewClientWrapper(jaegerTracer)),
	)

	// 初始化微服务
	MicroServer.Init()
}
